import { login, logout, register } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  username: '',
  fullname: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_FULLNAME: (state, fullname) => {
    state.fullname = fullname
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    console.log('开始登录流程，用户信息:', { username, password: '******' })
    return new Promise((resolve, reject) => {
      console.log('准备调用登录API')
      login({ username: username.trim(), password: password })
        .then(response => {
          console.log('登录API调用成功，原始响应:', response)

          // 检查response是否存在
          if (!response) {
            console.error('登录响应为空')
            reject(new Error('登录失败：服务器未返回数据'))
            return
          }

          // 检查data属性
          const { data } = response
          if (!data) {
            console.error('登录响应中没有data属性')
            reject(new Error('登录失败：响应数据格式错误'))
            return
          }

          console.log('登录响应data:', data)

          // 安全获取token - 尝试从多个可能的位置获取
          let token = null
          if (data.accessToken) {
            token = data.accessToken
          } else if (data.token) {
            token = data.token
          } else if (data.data && (data.data.accessToken || data.data.token)) {
            token = data.data.accessToken || data.data.token
          }

          // 检查是否获取到token
          if (!token) {
            console.error('未在响应中找到token，响应数据结构:', data)
            reject(new Error('登录失败：未获取到认证信息'))
            return
          }

          // 安全获取其他用户信息
          let roles = []
          let fullName = ''
          let responseUsername = username // 默认使用输入的用户名

          // 尝试从不同可能的数据结构中获取用户信息
          if (data.data) {
            roles = data.data.role || data.data.roles || []
            fullName = data.data.fullName || data.data.name || ''
            responseUsername = data.data.username || data.data.userName || username
          } else {
            roles = data.role || data.roles || []
            fullName = data.fullName || data.name || ''
            responseUsername = data.username || data.userName || username
          }

          // 确保roles是数组
          if (!Array.isArray(roles)) {
            roles = [roles]
            console.log('将非数组角色转换为数组:', roles)
          }

          console.log('登录成功，获取到的用户信息:', { token, roles, fullName, username: responseUsername })

          // 更新状态
          commit('SET_TOKEN', token)
          commit('SET_ROLES', roles)
          commit('SET_FULLNAME', fullName)
          commit('SET_USERNAME', responseUsername)

          // 保存token到cookie
          setToken(token)
          console.log('token已保存到cookie')

          resolve()
        })
        .catch(error => {
          console.error('登录API调用失败:', error)
          console.error('错误详情:', error.message, error.stack)
          reject(error)
        })
    })
  },
  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // user register
  register({ commit }, userInfo) {
    const { fullName, username, email, password } = userInfo
    return new Promise((resolve, reject) => {
      register({ fullName, username, email, password }).then(response => {
        console.log('注册成功:', response)
        resolve(response)
      }).catch(error => {
        console.error('注册失败:', error)
        reject(error)
      })
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
